package principal;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

import javax.swing.text.DateFormatter;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class ConvertidorFechaXML implements Converter{

	private Locale locale;
	
	public ConvertidorFechaXML(Locale locale){
		super();
		this.locale = locale;
	}
	
	@Override
	public boolean canConvert(Class type) {
		return Calendar.class.isAssignableFrom(type);
	}

	@Override
	public void marshal(Object source, HierarchicalStreamWriter writer,
			MarshallingContext context) {

		Calendar calendar = (Calendar) source;
		Date date = calendar.getTime();
		DateFormat formatter = DateFormat.getInstance().getDateInstance(DateFormat.SHORT,locale);
		writer.setValue(formatter.format(date));
		
	}

	@Override
	public Object unmarshal(HierarchicalStreamReader reader,
			UnmarshallingContext context) {

		GregorianCalendar calendar = new GregorianCalendar();
		DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT,locale);
		
		try {
			calendar.setTime(formatter.parse(reader.getValue()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		return calendar;
	}

}
